<!-- test.html -->

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>单词测试</title>
    <link rel="stylesheet" href="../plugins/elementui/index.css">
</head>
<body>
<div id="app">
    <!-- 顶部导航栏 -->
    <el-menu class="el-menu-demo" mode="horizontal">
        <el-menu-item @click="navigateHome">首页</el-menu-item>
        <el-menu-item @click="navigateToSelectChapter">重新选择章节</el-menu-item>
    </el-menu>

    <!-- 播放控制按钮 -->
    <div style="margin-bottom: 20px;">
        <el-button v-if="!isPlaying && !isPaused" type="primary" @click="startTest">开始测试</el-button>
        <el-button v-if="isPlaying" type="warning" @click="pauseAudio">暂停测试</el-button>
        <el-button v-if="isPaused" type="success" @click="resumeAudio">继续测试</el-button>
        <el-button type="primary" @click="openSettings">设置</el-button>
    </div>

    <!-- 测试表格 -->
    <el-table :data="testWords" style="width: 100%; table-layout: fixed;">
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column label="填写框" align="center">
            <template slot-scope="scope">
                <el-input v-model="scope.row.userAnswer" size="small" style="width: 90%;"></el-input>
            </template>
        </el-table-column>
    </el-table>

    <!-- 提交按钮 -->
    <el-button type="success" @click="submitTest" style="margin-top: 20px;">提交测试</el-button>

    <!-- 设置对话框 -->
    <el-dialog title="播放设置" :visible.sync="settingsDialogVisible" width="400px">
        <el-form label-width="120px">
            <el-form-item label="音频类型">
                <el-radio-group v-model="audioType" size="medium">
                    <el-radio-button label="usVoice">美音</el-radio-button>
                    <el-radio-button label="ukVoice">英音</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="每个单词播放次数">
                <el-input-number v-model="playCount" :min="1" :max="10" size="medium" style="width: 100%;"></el-input-number>
            </el-form-item>
            <el-form-item label="播放速度">
                <el-slider v-model="playbackRate" :min="0.5" :max="2" :step="0.1" show-tooltip></el-slider>
                <div style="text-align: center; margin-top: 10px;">{{ playbackRate }}x</div>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="settingsDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="applySettings">应用设置</el-button>
        </span>
    </el-dialog>
</div>

<!-- 引入 Vue 和 ElementUI -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            testWords: [],
            showResult: false,
            testResults: [],
            audioQueue: [],
            isPlaying: false,
            isPaused: false,
            currentAudio: null,
            selectedChapter: '',
            audioType: 'usVoice',
            playCount: 2,
            playbackRate: 1.0,
            settingsDialogVisible: false
        },
        created() {
            const urlParams = new URLSearchParams(window.location.search);
            this.selectedChapter = urlParams.get('chapter');
            this.loadTestWords();
        },
        methods: {
            navigateHome() {
                window.location.href = 'wangluwords.html';
            },
            navigateToSelectChapter() {
                window.location.href = 'select-chapter.html';
            },
            openSettings() {
                this.settingsDialogVisible = true;
            },
            applySettings() {
                this.settingsDialogVisible = false;
            },
            loadTestWords() {
                axios.get(`/wanglu/test/words?chapter=${this.selectedChapter}`).then((res) => {
                    this.testWords = res.data.data;
                }).catch(error => {
                    console.error('获取单词失败: ', error);
                });
            },
            startTest() {
                this.audioQueue = this.testWords.flatMap(word => Array(this.playCount).fill(word[this.audioType]));
                this.isPlaying = true;
                this.isPaused = false;
                this.playNextInQueue();
            },
            playNextInQueue() {
                if (this.audioQueue.length === 0) {
                    this.isPlaying = false;
                    return;
                }
                const audioUrl = this.audioQueue.shift();
                this.currentAudio = new Audio(audioUrl);
                this.currentAudio.playbackRate = this.playbackRate;
                this.currentAudio.addEventListener('ended', () => this.playNextInQueue());
                this.currentAudio.play().catch(error => {
                    console.error("音频播放失败: ", error);
                });
            },
            pauseAudio() {
                if (this.currentAudio) {
                    this.currentAudio.pause();
                    this.isPlaying = false;
                    this.isPaused = true;
                }
            },
            resumeAudio() {
                if (this.currentAudio) {
                    this.currentAudio.play();
                    this.isPlaying = true;
                    this.isPaused = false;
                }
            },
            submitTest() {
                axios.post('/wanglu/test/submit', {
                    chapter: this.selectedChapter,
                    answers: this.testWords.map(word => ({
                        wordId: word.id,
                        // 在这里，word.userAnswer || "" 的逻辑会确保如果 userAnswer 是 undefined，则会将其设为空字符串。
                        userAnswer: word.userAnswer || ""
                    }))
                }).then(res => {
                    // 将结果存储在 sessionStorage 中
                    sessionStorage.setItem('testResults', JSON.stringify(res.data.data));
                    // 跳转到 test-result.html 页面
                    window.location.href = 'test-result.html';
                }).catch(error => {
                    console.error('提交测试失败: ', error);
                });
            }
        }
    });
</script>
</body>
</html>